<template>
  <ProTable
    ref="tableRef"
    :fetchListApi="_getList"
    :columns="columns"
    :row-selection="rowSelection"
    row-key="msgId"
  >
    <template #toolbars>
      <Space>
        <b-button icon="add" @click="onAdd" v-if="!isRapid" code="drill:add"
          >新增演练</b-button
        >
        <b-button
          icon="delete"
          :disabled="!selectKeys?.length"
          @click="onDelete"
          code="drill:remove"
          >删除</b-button
        >
      </Space>
    </template>
    <template #operation="{ record }">
      <b-button
        type="link"
        icon="detail"
        code="drill:query"
        @click="onView(record)"
        >详情</b-button
      >
      <b-button
        @click="() => onAudit(record)"
        type="link"
        icon="detail"
        v-if="record.approveStatus == '0' && !isRapid"
        code="drill:approve"
        >审核</b-button
      >
      <b-button
        @click="() => onPush(record)"
        type="link"
        icon="detail"
        v-if="record.pushButton == '1' && !isRapid"
        :disabled="!record.onlineStatus"
        code="drill:pull"
        >推送</b-button
      >
      <b-button
        @click="() => onRecord(record)"
        type="link"
        icon="detail"
        :disabled="record.pushCount <= 0"
        code="drillPushTotalLog:query"
        >记录</b-button
      >
    </template>
    <template #info="{ record }">
      <div class="eewMessage">
        <div>
          <div style="flex: 1">震级：</div>
          <div style="flex: 3">{{ record.magnitude || '--' }}级</div>
        </div>
        <div>
          <div style="flex: 1">烈度：</div>
          <div style="flex: 3">{{ record.epiintensity || '--' }}°</div>
        </div>
        <div>
          <div style="flex: 1">深度：</div>
          <div style="flex: 3">{{ record.focdepth || '--' }}km</div>
        </div>
        <div>
          <div style="flex: 1">经度：</div>
          <div style="flex: 3">{{ record.epilon || '--' }}°</div>
        </div>
        <div>
          <div style="flex: 1">纬度：</div>
          <div style="flex: 3">{{ record.epilat || '--' }}°</div>
        </div>
        <div>
          <div style="flex: 1">地名：</div>
          <div style="flex: 3">{{ record.locname || '--' }}</div>
        </div>
      </div>
    </template>
    <template #drillProjectVOS="{ record }">
      <!--  -->
      <Tree
        style="height: 130px; overflow-y: auto"
        defaultExpandAll
        :tree-data="record.drillProjectVOS"
        :fieldNames="{
          children: 'children',
          title: 'name',
          key: 'key',
        }"
      >
        <template #title="{ dataRef, data }">
          <span v-if="data.id">{{ dataRef.name }}</span>
          <span
            v-else-if="data.children"
            v-html="dataRef.name"
            :style="{
              color: data.onlineStatus == '1' ? '#67C23A' : '#F56C6C',
            }"
          ></span>
          <span v-else v-html="dataRef.name"> </span>
        </template>
      </Tree>
    </template>
  </ProTable>
  <!-- 记录 -->
  <FormModal :items="items">
    <template #details>
      <div class="modal_table_only">
        <ProTable
          :fetchListApi="_pushTotalLog"
          hideSearch
          :columns="modalColumns"
        >
          <template #failCount="{ record }">
            <span
              style="color: #409eff; cursor: pointer"
              @click="onModalView(record, '0')"
              >{{ record.failCount }}</span
            >
          </template>
          <template #pushBy="{ record }">
            <span style="color: #409eff">{{ record.pushBy }}</span>
          </template>
          <template #operation="{ record }">
            <b-button
              @click="() => onModalView(record)"
              type="link"
              icon="detail"
              >查看</b-button
            >
            <b-button @click="() => onMessage(record)" type="link" icon="detail"
              >报文</b-button
            >
          </template>
        </ProTable>
      </div>
    </template>
  </FormModal>
  <!-- 预警演练推送设备列表 -->
  <FormModal2 :items="items">
    <template #details>
      <ProTable
        :fetchListApi="_weatherlogList"
        hideSearch
        :height="200"
        :columns="pushColumns"
      >
        <template #pushStatus="{ record }">
          <span v-if="record.pushStatus == '1'" style="color: #67c23a"
            >成功</span
          >
          <span v-else style="color: #f56c6c">失败</span>
        </template>

        <template #onlineStatus="{ record }">
          <Tag :color="record.onlineStatus == 1 ? 'success' : 'danger'">{{
            record.onlineStatus == 1 ? '在线' : '离线'
          }}</Tag>
        </template>
      </ProTable>
    </template>
  </FormModal2>

  <!-- 报文 -->
  <FormModal3 :items="items">
    <template #details>
      <JsonViewer
        :value="messageData"
        :expand-depth="5"
        style="background: transparent"
        :copyable="{ copyText: '复制', copiedText: '已复制!' }"
        sort
      ></JsonViewer>
    </template>
  </FormModal3>

  <!-- 推送弹窗 -->
  <FormModal5 :items="[]">
    <template #after-content="{ visible }">
      <div class="process">
        <Progress
          type="circle"
          :percent="num"
          v-show="+num.toFixed(0) < 100"
        ></Progress>
        <Result
          status="success"
          title="推送完成"
          v-show="+num.toFixed(0) >= 100"
        >
          <template #extra>
            <b-button @click="onBack(visible)">返回列表</b-button>
          </template>
        </Result>
      </div>
      <div class="info">
        <div class="title">
          <span>全部 {{ dataList.length || 0 }}</span>
          <span>推送失败 {{ lose || 0 }}</span>
          <span>推送成功 {{ succeed || 0 }}</span>
        </div>
        <div class="content">
          <Table
            ref="selectRef"
            style="height: 100%"
            :dataSource="dataList"
            :scroll="{ y: 150 }"
            :columns="pushColumns2"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.dataIndex === 'pushStatus'">
                <span v-if="record.pushStatus == '1'" style="color: #67c23a"
                  >成功</span
                >
                <span v-else style="color: #f56c6c">失败</span>
              </template>
            </template>
          </Table>
        </div>
      </div>
    </template>
  </FormModal5>

  <!-- 新增 -->
  <FormModal4 :items="formItems">
    <template #customFooter="{ formState, visible }" v-if="isAudit">
      <div>
        <b-button @click="onCancel(visible)">取消</b-button>
        <b-button @click="onPass(formState, visible)">通过</b-button>
      </div>
    </template>
    <template #details>
      <div class="custom_title">
        <div>
          信息接收对象(已选
          <span style="color: #409eff; font-weight: 600">{{
            mockData.length
          }}</span>
          个)
        </div>
        <div>
          <b-button :disabled="isInfo" icon="add" @click="onSelect"
            >新增</b-button
          >
        </div>
      </div>
      <Table
        ref="selectRef"
        :dataSource="mockData"
        :columns="selectColumns"
        row-key="deviceId"
        defaultExpandAllRows
        :scroll="{ y: 400 }"
      >
        <template #bodyCell="{ column, text, record }">
          <template v-if="column.dataIndex === 'onlineStatus'">
            <Tag :color="text == 1 ? 'success' : 'error'">{{
              text == 1 ? '在线' : '离线'
            }}</Tag>
          </template>

          <template v-if="column.dataIndex === 'operation'">
            <b-button @click="onRemove(column, record)" :disabled="isInfo"
              >移除</b-button
            >
          </template>
        </template>
        <template #expandedRowRender="{ record }">
          <Table
            ref="selectRef"
            :dataSource="record.obj"
            :columns="childColumns"
            :scroll="{ y: 400 }"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.dataIndex === 'level'">
                <span>{{ lvTwo(record.level) }}</span>
              </template>
            </template>
          </Table>
        </template>
      </Table>
      <div class="card-container">
        <div class="title">
          <div>设置事件位置</div>
          <div></div>
        </div>
        <div style="padding: 20px 20px; height: 400px; position: relative">
          <div class="earthquake-info">
            <Row class="earthquake-left" v-show="topForm.epilon">
              <Col
                :span="24"
                style="border-bottom: 1px solid rgba(242, 242, 242, 0.2)"
              >
                震源信息</Col
              >
              <Col :span="12">
                <span>震源经度：</span
                ><span>{{ topForm.epilon ? topForm.epilon + '°' : '' }}</span>
              </Col>
              <Col :span="12">
                <span>震源纬度：</span
                ><span>{{ topForm.epilat ? topForm.epilat + '°' : '' }}</span>
              </Col>
              <Col :span="12">
                <span>震中烈度：</span
                ><span>{{
                  topForm.epiintensity ? topForm.epiintensity + '°' : ''
                }}</span>
              </Col>
              <Col :span="12">
                <span>震级：</span><span>{{ topForm.magnitude || '' }}</span>
              </Col>

              <Col :span="24">
                <span>震中地名：</span><span>{{ topForm.locname || '' }}</span>
              </Col>
            </Row>
            <Row class="earthquake-right" v-if="mockData.length > 0">
              <Col
                :span="24"
                style="border-bottom: 1px solid rgba(242, 242, 242, 0.2)"
              >
                设备信息</Col
              >
              <Col :span="12">
                <span>设备经度：</span
                ><span>{{
                  mockData[0].longitude
                    ? Number(mockData[0].longitude).toFixed(3) + '°'
                    : ''
                }}</span>
              </Col>
              <Col :span="12">
                <span>设备纬度：</span
                ><span>{{
                  mockData[0].latitude
                    ? Number(mockData[0].latitude).toFixed(3) + '°'
                    : ''
                }}</span>
              </Col>
              <Col :span="12">
                <span> 震 源 距 ：</span
                ><span>{{
                  mockData[0].obj
                    ? Math.round(mockData[0].obj[0].distance) + 'km'
                    : ''
                }}</span></Col
              >
              <Col :span="12">
                <span>预估烈度：</span
                ><span>{{
                  mockData[0].obj ? mockData[0].obj[0].localIntensity + '°' : ''
                }}</span></Col
              >
              <Col :span="24">
                <span>设备位置：</span><span>{{ deviceAddress }}</span></Col
              >
            </Row>
          </div>

          <LbsMap
            :markers="markers"
            :center="LbsCenter"
            @click="onClick"
          ></LbsMap>
        </div>
      </div>
    </template>
    <template #view="{ formState }">
      <b-button @click="onViewRules(formState)">查看</b-button>
    </template>
    <template #effectTime="{ modalType, formState, visible }">
      <FormItemRest>
        <div class="custom_date">
          <div class="checked">
            <span style="margin-right: 10px">立即生效</span>
            <Checkbox v-model:checked="checked"></Checkbox>
          </div>
          <div v-show="!checked">
            <DatePicker
              show-time
              valueFormat="YYYY-MM-DD HH:mm:ss"
              v-model:value="formState.effectTime"
            ></DatePicker>
          </div>
        </div>
      </FormItemRest>
    </template>
  </FormModal4>
  <!-- 查看规则 -->
  <FormModal6 :items="items">
    <template #details>
      <Table
        style="height: 100%"
        :dataSource="ruleList"
        :scroll="{ y: 400 }"
        :columns="ruleColumns"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'intensity'">
            <Space :size="8">
              <Tag
                v-for="(item, index) in record.intensity"
                :key="index"
                :color="formatColor(record.level)"
                effect="dark"
                >{{ item }}</Tag
              >
            </Space>
          </template>
        </template>
      </Table>
    </template>
  </FormModal6>

  <FormModal7 :items="items">
    <template #details>
      <FormItemRest>
        <ProTable
          :fetchListApi="_getDevice"
          :height="600"
          :columns="warnColumns"
          :row-selection="warnSelection"
          row-key="deviceId"
        >
          <template #onlineStatus="{ record }">
            <Tag :color="record.onlineStatus == 1 ? 'success' : 'error'">{{
              record.onlineStatus == 1 ? '在线' : '离线'
            }}</Tag>
          </template>
        </ProTable>
      </FormItemRest>
    </template>
    <template #customFooter="{ formState, visible }">
      <b-button @click="onSelected(visible)">确定</b-button>
    </template>
  </FormModal7>
</template>

<script setup lang="tsx">
import { computed, ref, watch } from 'vue';
import {
  Checkbox,
  Col,
  DatePicker,
  FormItemRest,
  Modal,
  Progress,
  Result,
  Row,
  Select,
  Space,
  Table,
  Tag,
  Tree,
  TreeSelect,
  message,
} from 'ant-design-vue';
import dayjs from 'dayjs';
import { pick } from 'lodash-es';
import JsonViewer from 'vue-json-viewer';
import { hasPermission } from '@/permission/index';
import { ProFormProps } from '@/components/ProForm';
import { ProTable, ProTableProps } from '@/components/ProTable/index';
import { useFormModal } from '@/hooks/formModal';
import { listToEnum, treeToArray } from '@/utils/utils';
import { auditStatusEnum } from '@/constant/push';
import { getDictType } from '@/api/monitor';
import { saveRecord } from '@/api/notice';
import {
  getAddress,
  getAddressNew,
  getDetailsDrill,
  getDevice,
  getFailLogByMsgId,
  getList,
  getPushIndex,
  getPushLogByMsgId,
  handleAddDrill,
  handleApprove,
  handleDel,
  handleEdit,
  handlePush,
  warningCountdown,
} from '@/api/push';
import CustomTree from '../components/customTree.vue';
import LbsMap from '../components/map.vue';
import { drillsStore } from '../store';

const typeEnum: any = ref();
const dictInit = () => {
  getDictType('device_operate_type').then((res) => {
    typeEnum.value = listToEnum(res.data as any, 'dictLabel', 'dictCode');
  });
};

dictInit();

const {
  refreshStore,
  deviceModeEnum,
  eventTypeOptions,
  eventTypeEnum,
  warmList,
  projectList,
  getModelEnum,
} = drillsStore();
const tableRef = ref();

const init = () => {
  refreshStore.warningDrill();
};

init();
const _getDevice = async (params: any) => {
  const queryParams = {
    ...params,
    onlineStatus: '1',
  };
  const res = await getDevice(queryParams);
  const { rows, total } = res;
  return {
    rows,
    total,
  };
};

const _getList = async (params: any) => {
  const queryParams = {
    ...params,
    msgType: 0,
  };
  const res = await getList(queryParams);
  const { rows, total } = res;
  const newRows = processData(rows);
  return {
    rows: newRows,
    total,
  };
};
const formatlevel = (val: any) => {
  switch (val) {
    case '无预警':
      return '无预警（灰色）';
    case 'Ⅳ级':
      return '蓝色预警';
    case 'Ⅲ级':
      return '黄色预警';
    case 'Ⅱ级':
      return '橙色预警';
    case 'Ⅰ级':
      return '红色预警';
    default:
      break;
  }
};

const formatColor = (val: any) => {
  switch (val) {
    case '无预警':
      return 'grey';
    case 'Ⅳ级':
      return '#409EFF';
    case 'Ⅲ级':
      return 'yellow';
    case 'Ⅱ级':
      return 'orange';
    case 'Ⅰ级':
      return 'red';
    default:
      break;
  }
};

const processData = (data: any) => {
  data.forEach((item: any, index: any) => {
    if (item.drillProjectVOS.length > 0) {
      item.drillProjectVOS.forEach((drill: any) => {
        drill.children.forEach((obj: any, i: any) => {
          if (obj.onlineStatus == '1') {
            obj.name = obj.code + '(在线)';
            item.onlineStatus = true;
          } else {
            obj.name = obj.code + '(离线)';
            if (!item.onlineStatus) {
              item.onlineStatus = false;
            }
          }
          obj.children[0].name = `
        预警等级：${formatlevel(obj.children[0].warningLevel)}<br/>
        震中距：${obj.children[0].distance}km<br/>
        本地烈度：${Math.round(obj.children[0].localIntensity)}°<br/>
        预警倒计时：${obj.children[0].localWarningTime}s`;
        });
      });
    }
  });
  return data;
};

const messageData = ref({});
const selectKeys = ref<number[]>([]);
const rowSelection = computed<ProTableProps['rowSelection']>(() => {
  return {
    selectedRowKeys: selectKeys.value,
    onChange(values) {
      selectKeys.value = values as number[];
    },
  };
});
const isRapid = ref(false);
const columns = computed<ProTableProps['columns']>(() => [
  {
    title: '预警来源',
    dataIndex: 'warningSource',
    defaultValue: '2',
    hideInTable: true,
    customSearchRender(formState) {
      const option = [
        { label: '预警演练', value: '2' },
        { label: '快速预警', value: '1' },
      ];
      const onChange = (value: any) => {
        isRapid.value = value == '1';
        tableRef.value.search();
      };
      return (
        <Select
          options={option}
          v-model:value={formState.warningSource}
          onChange={onChange}
        ></Select>
      );
    },
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    isTime: true,
  },
  {
    title: '生效时间',
    dataIndex: 'effectTime',
    hideInSearch: true,
  },
  {
    title: '震中地名',
    dataIndex: 'locname',
    hideInTable: true,
  },
  {
    title: '信息类型',
    dataIndex: 'msgType',
    hideInSearch: true,
    valueEnum: {
      ...eventTypeEnum.value,
    },
  },
  {
    title: '演练地震事件信息',
    dataIndex: 'info',
    hideInSearch: true,
  },
  {
    title: '信息接收对象',
    dataIndex: 'drillProjectVOS',
    // width: 220,
    hideInSearch: true,
  },
  // {
  //   title: '审核状态',
  //   dataIndex: 'approveStatus',
  //   hideInSearch: true,
  //   width: 100,
  //   customRender({ text }) {
  //     return (
  //       <Tag color={text == '1' ? 'success' : 'error'}>
  //         {auditStatusEnum[text as keyof typeof auditStatusEnum]}
  //       </Tag>
  //     );
  //   },
  // },
  {
    title: '推送次数',
    dataIndex: 'pushCount',
    hideInSearch: true,
  },
  {
    title: '操作人',
    dataIndex: 'updateBy',
    hideInSearch: true,
  },
  {
    title: '操作',
    fixed: 'right',
    dataIndex: 'operation',
    width: 220,
    hideInSearch: true,
  },
]);

const modalColumns = computed<ProTableProps['columns']>(() => [
  {
    title: '推送时间',
    dataIndex: 'pushTime',
    hideInSearch: true,
  },
  {
    title: '推送人',
    dataIndex: 'pushBy',
    hideInSearch: true,
  },
  {
    title: '推送总数',
    dataIndex: 'totalCount',
    hideInSearch: true,
  },
  {
    title: '推送成功数',
    dataIndex: 'successCount',
    hideInSearch: true,
  },
  {
    title: '推送失败数',
    dataIndex: 'failCount',
    hideInSearch: true,
  },
  {
    title: '操作',
    dataIndex: 'operation',
    hideInSearch: true,
    width: 160,
  },
]);

const pushColumns = computed<ProTableProps['columns']>(() => [
  {
    title: '推送时间',
    dataIndex: 'pushTime',
    hideInSearch: true,
  },
  {
    title: '设备序列号',
    dataIndex: 'deviceCode',
    hideInSearch: true,
  },
  {
    title: '站点名称',
    dataIndex: 'siteName',
    hideInSearch: true,
  },
  {
    title: '设备类型',
    dataIndex: 'deviceTypeLabel',
    hideInSearch: true,
  },
  {
    title: '设备型号',
    dataIndex: 'model',
    hideInSearch: true,
  },
  {
    title: '软件版本',
    dataIndex: 'softwareVersion',
    hideInSearch: true,
  },
  {
    title: '推送结果',
    dataIndex: 'pushStatus',
    hideInSearch: true,
  },
  {
    title: '状态',
    dataIndex: 'onlineStatus',
    hideInSearch: true,
  },
]);

const items = computed<ProFormProps['items']>(() => [
  {
    label: '',
    type: 'number',
    field: 'details',
  },
]);

const { FormModal, open } = useFormModal({
  size: 'middle',
  formProps: {
    wrapperCol: { span: 24 },
  },
});

const { FormModal: FormModal2, open: open2 } = useFormModal({
  size: 'middle',
  formProps: {
    wrapperCol: { span: 24 },
  },
});

const { FormModal: FormModal3, open: open3 } = useFormModal({
  size: 'small',
  formProps: {
    wrapperCol: { span: 24 },
  },
});

const code = ref();

const onRecord = async (record: any) => {
  code.value = record.msgId;
  open({
    title: '推送记录',
    modalType: 'add',
    defaultValue: {
      ...record,
    },
    hideFooter: true,
    serviceApi: async (params: any): Promise<any> => {},
  });
};

const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  pushStatus: '',
  drillPushTotalId: '',
});
const onModalView = async (record: any, status?: any) => {
  queryParams.value = {
    ...queryParams.value,
    ...pick(record, ['drillPushTotalId']),
    pushStatus: status ? status : '',
  };
  open2({
    title: status == '0' ? '预警演练推送失败设备列表' : '预警演练推送设备列表',
    modalType: 'disabled',
    defaultValue: {
      ...record,
    },
    hideFooter: true,
    serviceApi: async (params: any): Promise<any> => {},
  });
};

const onMessage = async (record: any) => {
  if (record.jsonData) {
    if (record.jsonData.indexOf('{') != -1) {
      messageData.value = JSON.parse(record.jsonData);
    } else {
      messageData.value = record.jsonData;
    }
  } else {
    messageData.value = {};
  }
  open3({
    title: '报文',
    modalType: 'disabled',
    defaultValue: {
      ...record,
    },
    hideFooter: true,
    serviceApi: async (params: any): Promise<any> => {},
  });
};

const sleep = (cb) => {
  setTimeout(() => {
    cb();
  }, 500);
};
const onDelete = async () => {
  Modal.confirm({
    title: '系统提示',
    content: `确认要删除当前选项？`,
    onOk: async () => {
      await handleDel(selectKeys.value);
      sleep(() => tableRef.value.refresh());
      selectKeys.value = [];
    },
  });
};

const _pushTotalLog = async (params: any) => {
  const res = await getPushLogByMsgId(code.value, params);
  const { rows, total } = res;
  return {
    rows,
    total,
  };
};

const _weatherlogList = async () => {
  const res = await getFailLogByMsgId(queryParams.value);
  const { rows, total } = res;
  return {
    rows,
    total,
  };
};
const isAudit = ref(false);
// 审核
const onAudit = async (record: any) => {
  matchingRule(record.levelConfigName);
  isAudit.value = true;
  topForm.value = record;
  isInfo.value = true;
  const res = await getDetailsDrill(record.msgId);
  if (res.code == 200) {
    mockData.value = res.data.deviceInfo;
  }
  getWarningCountdown();
  open4({
    title: '审核',
    modalType: 'disabled',
    defaultValue: {
      msgType: '2',
      epiintensity: 0,
      magnitude: 0,
      levelConfigName: '',
      ...record,
    },
    serviceApi: async (params: any): Promise<any> => {},
  });
};
const onCancel = (visible: any) => {
  visible.value = false;
};

const onPass = async (formState: any, visible: any) => {
  formState.approveStatus = '1';
  const params = pick(formState, ['approveStatus', 'msgId', 'effectTime']);
  const res = await handleApprove(params);
  if (res.code == 200) {
    visible.value = false;
    tableRef.value.refresh();
  }
};
// 推送
const num = ref(0);
const dataList: any = ref([]);
const succeed = ref(0);
const lose = ref(0);
const { FormModal: FormModal5, open: open5 } = useFormModal({
  size: 'middle',
  formProps: {
    wrapperCol: { span: 24 },
  },
});

const onPush = async (record: any) => {
  Modal.confirm({
    title: '系统提示',
    content: `是否确认推送预警信息？`,
    onOk: async () => {
      const result = await getPushIndex({ msgId: record.msgId });
      let deviceData: any = [];
      if (record.deviceInfo) {
        deviceData = [...record.deviceInfo];
      } else {
        record.drillProjectVOS.forEach((drill: any) => {
          deviceData.push(...drill.children);
        });
      }
      const list = deviceData.map((i: any) => {
        return {
          msgId: record.msgId,
          code: i.code,
          deviceId: i.deviceId,
          drillPushTotalId: result.data,
        };
      });
      const res = await handlePush(list);
      saveRecordFn(list, res, '推送', JSON.stringify(list), '/drillPushLog');
      if (res.code == 200) {
        num.value += 100;
        dataList.value = res.data;
        succeed.value = res.data.filter((i: any) => i.pushStatus == '1').length;
        lose.value = res.data.length - succeed.value;
        tableRef.value.refresh();
        open5({
          title: '推送进度',
          modalType: 'disabled',
          hideFooter: true,
          serviceApi: async (params: any): Promise<any> => {},
        });
      }
    },
  });
};

const saveRecordFn = async (
  data: any,
  res: any,
  operateButton: any,
  requestParam: any,
  operateUri: string,
) => {
  const list = data.map((item: any) => {
    return {
      deviceCode: item.code,
      operateModule: '推送管理/演练管理/预警演练',
      requestParam,
      status: res.code == 200 ? 1 : 0,
      operateButton,
      operateType: typeEnum.value[operateButton],
      operateUri,
    };
  });
  await saveRecord({ list });
};

const onBack = (visible: any) => {
  visible.value = false;
};

const pushColumns2 = computed<ProTableProps['columns']>(() => [
  {
    title: '推送状态',
    dataIndex: 'pushStatus',
    hideInSearch: true,
    align: 'center',
  },
  {
    title: '设备序列号',
    dataIndex: 'deviceCode',
    align: 'center',
    hideInSearch: true,
  },
  {
    title: '站点名称',
    dataIndex: 'siteName',
    align: 'center',
    hideInSearch: true,
  },
  {
    title: '设备类型',
    dataIndex: 'deviceTypeLabel',
    hideInSearch: true,
    align: 'center',
  },
  {
    title: '设备型号',
    dataIndex: 'model',
    hideInSearch: true,
    align: 'center',
  },
  {
    title: '软件版本',
    dataIndex: 'softwareVersion',
    hideInSearch: true,
    align: 'center',
  },
]);
// 新增
const {
  FormModal: FormModal4,
  open: open4,
  formRef,
} = useFormModal({
  size: 'middle',
  column: 2,
  onValuesChange: async (changeValues, formState) => {
    if (changeValues.hasOwnProperty('magnitude')) {
      const num = changeValues['magnitude'] || 0;
      formState['epiintensity'] = Math.round(num * 1.29 + 0.24);
    }
    const { epilat, epilon, focdepth } = formState;
    topForm.value = formState;
    if (
      epilon &&
      epilat &&
      changeValues.hasOwnProperty('epilat') &&
      changeValues.hasOwnProperty('epilon')
    ) {
      const res = await getAddressNew(epilon, epilat);
      console.log(res, 'res11111');
      if (res.data.configName) {
        formState.levelConfigName = res.data.configName;
      } else {
        formState.levelConfigName = '';
      }
      topForm.value.locname = res.data.address;
    }

    if (epilat && epilon && focdepth) {
      getWarningCountdown();
    }
    // 匹配规则
    if (changeValues.hasOwnProperty('levelConfigName')) {
      matchingRule(changeValues['levelConfigName']);
    }
  },
});
const mockData = ref([]);
watch(
  () => mockData.value,
  (val) => {
    if (val.length > 0) {
      getWarningCountdown();
    }
  },
);
const checked = ref(false);
const formItems = computed<ProFormProps['items']>(() => [
  {
    label: '信息类型',
    type: 'radio',
    field: 'msgType',
    labelCol: { style: { width: '120px' } },
    rules: [{ required: true, message: '请选择信息类型', trigger: 'blur' }],
    props: {
      options: eventTypeOptions.value,
    },
  },
  {
    label: '生效时间',
    type: 'date',
    field: 'effectTime',
    labelCol: { style: { width: '120px' } },
    rules: checked.value
      ? []
      : [{ required: true, message: '请选择生效时间', trigger: 'blur' }],
    props: {
      showTime: true,
    },
  },
  {
    label: '震级(M)',
    type: 'number',
    rules: [{ required: true, message: '请输入震级', trigger: 'blur' }],
    field: 'magnitude',
    labelCol: { style: { width: '120px' } },
    props: {
      max: 12,
      min: 0,
    },
  },
  {
    label: '震源深度(km)',
    type: 'input',
    rules: [{ required: true, message: '请输入震源深度', trigger: 'blur' }],
    field: 'focdepth',
    labelCol: { style: { width: '120px' } },
  },
  {
    label: '震中烈度(°)',
    type: 'input',
    field: 'epiintensity',
    labelCol: { style: { width: '120px' } },
    props: {
      disabled: true,
    },
  },
  {
    label: '经度(°)',
    type: 'input',
    field: 'epilon',
    rules: [{ required: true, message: '请输入经度', trigger: 'blur' }],
    labelCol: { style: { width: '120px' } },
  },
  {
    label: '纬度(°)',
    type: 'input',
    field: 'epilat',
    rules: [{ required: true, message: '请输入纬度', trigger: 'blur' }],
    labelCol: { style: { width: '120px' } },
  },
  {
    label: '预警配置',
    type: 'select',
    field: 'levelConfigName',
    labelCol: { style: { width: '120px' } },
    colProps: {
      span: 9,
    },
    props: {
      options: warmList.value,
      allowClear: false,
    },
  },
  {
    label: '',
    type: 'input',
    field: 'view',
    colProps: {
      span: 3,
    },
  },
  {
    label: '',
    type: 'number',
    field: 'details',
    wrapperCol: { span: 24 },
    colProps: {
      span: 24,
    },
  },
]);

const selectColumns = computed<ProTableProps['columns']>(() => [
  {
    title: '项目名称',
    dataIndex: 'projectName',
    align: 'center',
  },
  {
    title: '站点名称',
    dataIndex: 'siteName',
    align: 'center',
  },
  {
    title: '设备序列号',
    dataIndex: 'code',
    align: 'center',
  },
  {
    title: '设备类型',
    dataIndex: 'deviceType',
    align: 'center',
    customRender: ({ text }) => {
      return deviceModeEnum.value[text];
    },
  },
  {
    title: '在线状态',
    dataIndex: 'onlineStatus',
    align: 'center',
  },
  {
    title: '操作',
    dataIndex: 'operation',
    align: 'center',
    width: 80,
  },
]);

const childColumns = computed<ProTableProps['columns']>(() => [
  {
    title: '预警等级',
    dataIndex: 'level',
    align: 'center',
  },
  {
    title: '本地烈度(°)',
    dataIndex: 'localIntensity',
    align: 'center',
  },
  {
    title: '震中距(km)',
    dataIndex: 'distance',
    align: 'center',
  },
  {
    title: '预警倒计时(s)',
    dataIndex: 'localWarningTime',
    align: 'center',
  },
]);

const isInfo = ref();
const onAdd = async () => {
  warnKeys.value = [];
  isAudit.value = false;
  isInfo.value = false;
  topForm.value = {};
  mockData.value = [];
  open4({
    title: '新增',
    modalType: 'add',
    defaultValue: {
      msgType: '2',
      epiintensity: 0,
      magnitude: 0,
      levelConfigName: '',
    },
    serviceApi: async (params: any): Promise<any> => {
      if (checked.value) {
        params.effectTime = dayjs().format('YYYY-MM-DD HH:mm:ss');
      }
      const deviceId = mockData.value.map((item: any) => {
        return item.deviceId;
      });
      const queryParams = { ...params, deviceId };
      await handleAddDrill(queryParams);
      sleep(() => tableRef.value.refresh());
    },
  });
};
const topForm = ref({});
// 编辑
const onView = async (record: any) => {
  matchingRule(record.levelConfigName);
  isAudit.value = false;
  topForm.value = record;
  isInfo.value = true;
  const res: any = await getDetailsDrill(record.msgId);
  if (res.code == 200) {
    mockData.value = res.data.deviceInfo;
    warnKeys.value = res.data.deviceInfo.map((item: any) => item.deviceId);
  }
  getWarningCountdown();
  open4({
    title: (type) => (type === 'info' ? '详情' : '编辑'),
    modalType:
      record.approveStatus != '0' || isRapid.value ? 'disabled' : 'info',
    defaultValue: {
      msgType: '2',
      epiintensity: 0,
      magnitude: 0,
      levelConfigName: '',
      ...record,
    },
    onChangeModeType(modalType: any) {
      isInfo.value = modalType === 'info';
    },
    serviceApi: async (params: any): Promise<any> => {
      if (checked.value) {
        params.effectTime = dayjs().format('YYYY-MM-DD HH:mm:ss');
      }
      const deviceId = mockData.value.map((item: any) => {
        return item.deviceId;
      });
      const queryParams = { ...params, deviceId };
      await handleEdit(queryParams);
      sleep(() => tableRef.value.refresh());
    },
    hasEditPermission: hasPermission('drill:edit'),
  });
};
//查看规则
const { FormModal: FormModal6, open: open6 } = useFormModal({
  size: 'middle',
  formProps: {
    wrapperCol: { span: 24 },
  },
});

const ruleList: any = ref([]);
const onViewRules = (formState: any) => {
  if (!formState.levelConfigName && (!formState.epilat || !formState.epilon)) {
    return message.error('请输入经纬度！');
  }
  // 如果有经纬度/需调接口拿规则数据并展示
  open6({
    title: '查看',
    modalType: 'disabled',
    hideFooter: true,
    serviceApi: async (params: any): Promise<any> => {},
  });
};
const oneGrad = ref();
const twoGrad = ref();
const threeGrad = ref();
const fourGrad = ref();
const matchingRule = (val: any) => {
  const item = warmList.value.find((i: any) => i.name === val) || {};
  console.log(item, 'item');

  ruleList.value = item.levelConfigVOList;
  if (!ruleList.value || !ruleList.value.length) return;
  if (ruleList.value[0].intensity) {
    oneGrad.value = ruleList.value[0].intensity.slice(-1)[0];
  } else {
    oneGrad.value = null;
  }
  twoGrad.value = ruleList.value[1].intensity?.slice(-1)[0];
  threeGrad.value = ruleList.value[2].intensity?.slice(-1)[0];
  fourGrad.value = ruleList.value[3].intensity?.slice(-1)[0];
};

const lvTwo = (value: any) => {
  let lv = '无预警';
  let _value = Math.round(value);
  if (_value <= oneGrad.value) {
    lv = '无预警';
  } else if (_value > oneGrad.value && _value <= twoGrad.value) {
    lv = '蓝色预警';
  } else if (_value > twoGrad.value && _value <= threeGrad.value) {
    lv = '黄色预警';
  } else if (_value > threeGrad.value && _value <= fourGrad.value) {
    lv = '橙色预警';
  } else if (_value > fourGrad.value) {
    lv = '红色预警';
  }
  return lv;
};
const ruleColumns = computed<ProTableProps['columns']>(() => [
  {
    title: '烈度范围',
    dataIndex: 'intensity',
    align: 'center',
  },
  {
    title: '预警等级',
    dataIndex: 'level',
    align: 'center',
  },
  {
    title: '等级颜色',
    dataIndex: 'levelColor',
    align: 'center',
  },
  {
    title: '避震指导',
    dataIndex: 'guidance',
    align: 'center',
  },
]);

//新增信息接收对象
const { FormModal: FormModal7, open: open7 } = useFormModal({
  size: 'middle',
  formProps: {
    wrapperCol: { span: 24 },
  },
});

const onSelect = (record: any) => {
  open7({
    title: '选择接收对象',
    modalType: 'add',
    defaultValue: {
      ...record,
    },
    serviceApi: async (params: any): Promise<any> => {},
  });
};

const onRemove = (column: any, record: any) => {
  const index = mockData.value.findIndex(
    (i: any) => i.deviceId === record.deviceId,
  );
  warnKeys.value.splice(index, 1);
  mockData.value.splice(index, 1);
};

const onSelected = (visible: any) => {
  mockData.value = selectList.value;
  visible.value = false;
};

const warnKeys = ref<number[]>([]);
const selectList = ref<object[]>([]);
const warnSelection = computed<ProTableProps['rowSelection']>(() => {
  return {
    selectedRowKeys: warnKeys.value,
    onChange(values, all) {
      selectList.value = all;
      warnKeys.value = values as number[];
    },
  };
});

const warnColumns = computed<ProTableProps['columns']>(() => [
  {
    title: '项目名称',
    dataIndex: 'projectName',
    hideInSearch: true,
  },
  {
    title: '项目名称',
    dataIndex: 'projectId',
    hideInTable: true,
    customSearchRender(state) {
      return (
        <TreeSelect
          v-model:value={state.projectId}
          fieldNames={{ value: 'id' }}
          placeholder='请选择'
          treeData={projectList.value}
          treeCheckable={true}
          maxTagCount={0}
          allowClear={true}
          showCheckedStrategy={TreeSelect.SHOW_ALL}
          maxTagPlaceholder={(omittedValues) => {
            if (omittedValues.length == 1) {
              return omittedValues[0].label;
            } else if (
              omittedValues.length == treeToArray(projectList.value).length
            ) {
              return '全部';
            } else {
              return '多项目';
            }
          }}
        >
          {{
            title: ({ label, type }: any) => {
              return type == '1' ? (
                <span style='color:#bababa'>{label}</span>
              ) : (
                label
              );
            },
          }}
        </TreeSelect>
      );
    },
  },
  {
    title: '站点名称',
    dataIndex: 'siteName',
    hideInSearch: true,
  },
  {
    title: '设备序列号',
    dataIndex: 'code',
  },
  {
    title: '设备类型',
    dataIndex: 'deviceType',
    valueEnum: {
      ...deviceModeEnum.value,
    },
  },
  {
    title: '在线状态',
    dataIndex: 'onlineStatus',
    hideInSearch: true,
    valueEnum: {
      '1': '在线',
      '0': '离线',
    },
  },
  {
    title: '设备型号',
    dataIndex: 'modelId',
    hideInTable: true,
    valueEnum: {
      ...getModelEnum.value,
    },
  },
]);

// 地图描点
const markers = computed(() => {
  const marker = mockData.value.map((item: any) => {
    return {
      latLng: [item.latitude, item.longitude],
      isFocal: false,
      locname: item.locname,
    };
  });
  const { epilat, epilon, locname } = topForm.value;
  const newMarker =
    epilat && epilon
      ? [
          ...marker,
          {
            latLng: [epilat, epilon],
            isFocal: true,
            locname,
          },
        ]
      : marker;
  return newMarker;
});

// 地图中心点
const LbsCenter = computed(() => {
  const { epilat, epilon } = topForm.value;
  if (epilat && epilon) {
    return [epilat, epilon];
  }
  const item: any = mockData.value[0] || {
    latitude: 30.511,
    longitude: 114.202,
  };
  return [item.latitude, item.longitude];
});

const deviceAddress = ref('');

watch(
  () => mockData.value,
  async (item: any) => {
    if (!item.length) return;
    item.forEach(async (device, index) => {
      const res = await getAddress(device.longitude, device.latitude);
      if (index == 0) {
        deviceAddress.value = res.msg;
      }
      device.locname = res.msg;
    });

    console.log('触发');
  },
  { deep: true },
);

const getWarningCountdown = () => {
  const { epilat, epilon, focdepth, epiintensity } = topForm.value as any;
  if (epilat && epilon && focdepth && mockData.value) {
    mockData.value.forEach(async (item: any) => {
      const res: any = await warningCountdown({
        epilat, // 震源纬度
        epilon, //震源经度
        focdepth: Number(focdepth), //震源深度
        Epiintensity: epiintensity, //震源烈度
        localLatitude: item.latitude, //本地纬度
        localLongitude: item.longitude, //本地经度
        publishTime: format('yyyy-MM-dd HH:mm:ss.S', 0), //当前时间
        oritime: format('yyyy-MM-dd HH:mm:ss.S', 300), //发震时间
      });
      if (res.code == 200) {
        item['address'] = res.data.address;
        item['level'] = res.data.localIntensity;
        item['obj'] = [
          {
            level: res.data.localIntensity,
            localIntensity: Math.round(res.data.localIntensity),
            distance: res.data.distance,
            localWarningTime: res.data.localWarningTime,
          },
        ];
      }
    });
  }
};

// 格式化时间
const format = (fmt: any, Delay: any) => {
  let _date = new Date();
  var o: any = {
    'M+': _date.getMonth() + 1, //月份
    'd+': _date.getDate(), //日
    'h+': _date.getHours() % 12 == 0 ? 12 : _date.getHours() % 12, //小时
    'H+': _date.getHours(), //小时
    'm+': _date.getMinutes(), //分
    's+': _date.getSeconds(), //秒
    // "q+": Math.floor((_date.getMonth() + 3) / 3), //季度
    S: _date.getMilliseconds() + Delay, //毫秒
  };
  if (/(y+)/.test(fmt))
    fmt = fmt.replace(
      RegExp.$1,
      (_date.getFullYear() + '').substr(4 - RegExp.$1.length),
    );
  for (var k in o)
    if (new RegExp('(' + k + ')').test(fmt))
      fmt = fmt.replace(
        RegExp.$1,
        RegExp.$1.length == 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length),
      );
  return fmt;
};
const onClick = async (latlng: any) => {
  const epilon = latlng[1].toFixed(3);
  const epilat = latlng[0].toFixed(3);
  topForm.value.epilat = epilat;
  topForm.value.epilon = epilon;
  formRef.value.setFiledValue('epilat', epilat);
  formRef.value.setFiledValue('epilon', epilon);
  //const result = await getAddress(epilon, epilat);
  //topForm.value.locname = result.msg || '-';
};
</script>

<style scoped lang="scss">
.custom_title {
  display: flex;
  margin-bottom: 10px;
  justify-content: space-between;
  align-items: center;
}

.eewMessage {
  > div {
    margin-bottom: 10px;
    display: flex;
    text-align: left;
    &:last-child {
      margin-bottom: 0;
    }
  }
}

.process,
.info {
  width: 100%;
  height: 300px;
  background-color: rgba(0, 0, 0, 0.3);
  border-radius: 8px;
}
.process {
  display: flex;
  justify-content: center;
  align-items: center;
  // text-align: center;
  // line-height: 300px;
}
.info {
  padding: 15px 20px;
  margin-top: 20px;
  .title {
    padding: 8px;
    span {
      margin-right: 50px;
      position: relative;
      &:first-child {
        color: #000;
        padding-right: 30px;
        margin-right: 30px;
        border-right: 1px solid #909399;
      }
      &:nth-child(2),
      &:nth-child(3) {
        color: #909399;
        &::before {
          position: absolute;
          top: 50%;
          left: -15px;
          transform: translateY(-50%);
          content: '';
          display: block;
          width: 7px;
          height: 7px;
          border-radius: 50%;
          background-color: #ff0000;
        }
      }
      &:nth-child(3) {
        &::before {
          background: #52c41a;
        }
      }
    }
  }
}
.custom_date {
  display: flex;
  align-items: center;
  .checked {
    margin-right: 60px;
  }
}
.card-container {
  padding-top: 20px;
}

.earthquake-info {
  position: absolute;
  left: 0;
  width: 100%;
  height: 100%;
  > div {
    position: absolute;
    top: 18px;
    background: rgba(1, 25, 28, 0.77);
    z-index: 999;
    padding: 10px 20px;
    width: 340px;
    color: #fff;
    border-radius: 4px;
  }
  .earthquake-left {
    left: 38px;
  }
  .earthquake-right {
    right: 38px;
  }
  .el-row {
    > div {
      padding: 5px 0;
    }
  }
  .svg-earthquake {
    width: 1em;
    height: 1em;
    vertical-align: text-top;
    margin-right: 8px;
  }
}
</style>
<style>
.ant-tree-node-content-wrapper {
  text-align: left !important;
}
</style>
